/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.mapper.*;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.system.service.CourseresourcesauditlogService;
import me.zhengjie.modules.system.domain.vo.CourseresourcesauditlogQueryCriteria;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import me.zhengjie.utils.PageResult;

/**
* @description 服务实现
* @author shitou
* @date 2024-12-12
**/
@Service
@RequiredArgsConstructor
public class CourseresourcesauditlogServiceImpl extends ServiceImpl<CourseresourcesauditlogMapper, Courseresourcesauditlog> implements CourseresourcesauditlogService {

    private final CourseresourcesauditlogMapper courseresourcesauditlogMapper;

    private final UserMapper userMapper;

    private final TeacherMapper teacherMapper;

    private final CourseresourcescatalogMapper courseresourcescatalogMapper;

    private final CourseresourcesMapper courseresourcesMapper;

    @Override
    public PageResult<Courseresourcesauditlog> queryAll(CourseresourcesauditlogQueryCriteria criteria, Page<Object> page){
        IPage<Courseresourcesauditlog> courseresourcesauditlogIPage = courseresourcesauditlogMapper.findAll(criteria, page);

        List<Integer> createUserIds = new ArrayList<>();
        List<Courseresourcesauditlog> courseresourcesauditlogList = courseresourcesauditlogIPage.getRecords();
        for(Courseresourcesauditlog courseresourcesauditlog:courseresourcesauditlogList){

            createUserIds.add(courseresourcesauditlog.getUserId());
        }

        //获取创建资源用户用户
        List<User> userList = new ArrayList<>();
        if(createUserIds.size()!=0){
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("user_id",createUserIds);
            userList = userMapper.selectList(queryWrapper);
        }


        for(Courseresourcesauditlog courseresourcesauditlog:courseresourcesauditlogList){

            for(User user:userList){
                if(courseresourcesauditlog.getUserId()!=null && courseresourcesauditlog.getUserId() == Math.toIntExact(user.getId())){
                    courseresourcesauditlog.setNickName(user.getNickName());
                }
            }
        }
        courseresourcesauditlogIPage.setRecords(courseresourcesauditlogList);
        return PageUtil.toPage(courseresourcesauditlogIPage);
    }

    @Override
    public List<Courseresourcesauditlog> queryAll(CourseresourcesauditlogQueryCriteria criteria){

        List<Courseresourcesauditlog> courseresourcesauditlogList = courseresourcesauditlogMapper.findAll(criteria);
        List<Integer> createUserIds = new ArrayList<>();
        for(Courseresourcesauditlog courseresourcesauditlog:courseresourcesauditlogList){

            createUserIds.add(courseresourcesauditlog.getUserId());
        }

        //获取创建资源用户用户
        List<User> userList = new ArrayList<>();
        if(createUserIds.size()!=0){
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("user_id",createUserIds);
            userList = userMapper.selectList(queryWrapper);
        }


        for(Courseresourcesauditlog courseresourcesauditlog:courseresourcesauditlogList){

            for(User user:userList){
                if(courseresourcesauditlog.getUserId()!=null && courseresourcesauditlog.getUserId() == Math.toIntExact(user.getId())){
                    courseresourcesauditlog.setNickName(user.getNickName());
                }
            }
        }

        return courseresourcesauditlogList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Courseresourcesauditlog resources) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",currentUser.getId());
        Teacher teacher = teacherMapper.selectOne(queryWrapper);


        if(teacher!=null){
            resources.setTeacherId(Math.toIntExact(teacher.getId()));
        }
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式化器，使用 yyyy-MMM-dd hh:mm:ss 格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd hh:mm:ss");
        // 将 LocalDateTime 按照定义的格式进行格式化
        String formattedDateTime = now.format(formatter);

        resources.setCreateTime(formattedDateTime);
        resources.setUserId(Math.toIntExact(currentUser.getId()));

        Courseresourcescatalog courseresourcescatalog = new Courseresourcescatalog();
        courseresourcescatalog.setId(resources.getCourseResourcesCatalogId());
        courseresourcescatalog.setCourseresourcesId(resources.getCourseResourcesId());
        courseresourcescatalog.setState(resources.getState());
        if(resources.getState() == 1){
            courseresourcescatalog.setCreateTime(formattedDateTime);
        }

        courseresourcescatalogMapper.updateById(courseresourcescatalog);

        List<Courseresourcescatalog> courseresourcesauditlogList = new ArrayList<>();

//        QueryWrapper queryWrapper1 = new QueryWrapper<>();
//        queryWrapper1.eq("CourseresourcesId",resources.getCourseResourcesId());
//        courseresourcesauditlogList = courseresourcescatalogMapper.selectList(queryWrapper1);

//        Integer status = 0;
//        for(Courseresourcescatalog courseresourcescatalog1:courseresourcesauditlogList){
//            if(courseresourcescatalog1.getState() == null || courseresourcescatalog1.getState() !=2){
//                status = 1;
//            }
//        }
//        if(status == 0){
//            Courseresources courseresources = new Courseresources();
//            courseresources.setId(resources.getCourseResourcesId());
//            courseresources.setState(1);
//            courseresourcesMapper.updateById(courseresources);
//        } else {
            Courseresources courseresources = new Courseresources();
            courseresources.setId(resources.getCourseResourcesId());
            courseresources.setState(resources.getState());
            courseresourcesMapper.updateById(courseresources);
//        }


        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Courseresourcesauditlog resources) {
        Courseresourcesauditlog courseresourcesauditlog = getById(resources.getId());
        courseresourcesauditlog.copy(resources);
        saveOrUpdate(courseresourcesauditlog);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Courseresourcesauditlog> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Courseresourcesauditlog courseresourcesauditlog : all) {
            Map<String,Object> map = new LinkedHashMap<>();
//            map.put(" courseresourcesId",  courseresourcesauditlog.getCourseresourcesId());
//            map.put(" courseresourcescatalogId",  courseresourcesauditlog.getCourseresourcescatalogId());
            map.put("content",  courseresourcesauditlog.getContent());
            map.put("teacherId",  courseresourcesauditlog.getTeacherId());
            map.put("state",  courseresourcesauditlog.getState());
//            map.put("createTime",  courseresourcesauditlog.getCreatetime());
            map.put("lastupdateTime",  courseresourcesauditlog.getLastupdatetime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}